package hxy.bytecode.designpattern;

public class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {
    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    //volatile保证，当uniqueInstance变量被初始化成Singleton实例时，多个线程可以正确处理 uniqueInstance变量
    private volatile static Singleton uniqueInstance;

    public static Singleton getInstance() {
//检查实例，如果不存在，就进入同步代码块
        if (uniqueInstance == null) {
//只有第一次才彻底执行这里的代码
            synchronized (Singleton.class) {
//进入同步代码块后，再检查一次，如果仍是null，才创建实例
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }

    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        if (singleton == null) {
            System.out.println("Singletom is null");
        } else {
            System.out.println("Singletom is not null");
        }
        Singleton singleton1 = Singleton.getSingleton();

        if (singleton == singleton1) {
            System.out.println("equal");
        }
    }

}